/**
 * 
 */
package org.dragonfire.dasm.linkers;

import java.util.ArrayList;
import java.util.List;

import org.dragonfire.dasm.DASM;
import org.dragonfire.ti.TIFile;

/**
 * This linker creates *.8xp files for use with the TI-83+, TI-83+SE, TI-84+,
 * and TI-84+SE brand of graphing calculators. The "<code>lock</code>"
 * parameter is used to decide whether the produced program should be protected
 * or not (editable on the calculator). For most assemblies, this is undesirable
 * and therefore the default is to lock generated files.
 * 
 * @author Darth Android
 * @version 2.0
 */
public class Linker83p extends Linker {

	/**
	 * The default on whether to lock the produced files or not if the
	 * <code>--lock</code> or <code>--no-lock</code> arguments aren't used
	 */
	public static final boolean LOCK_FILES = true;
	/**
	 * The default comment that is put into the files<br />
	 * This can be overridden by the <code> argument
	 */
	public static final String COMMENT = "Built by DASM v" + DASM.VERSION + " " + DASM.VERSION_APPEND;

	@Override
	public List<Byte> link(DASM comp, List<Byte> data) {
		TIFile tif = new TIFile(TIFile.CALC_83, COMMENT);
		if (comp.getParam("comment") != null)
			tif.setComment(comp.getParam("comment"));
		String name = comp.getParam("outputfile");
		// name - Strip leading path, extension, and unwanted chars
		name = name.replaceAll(".*[\\\\\\/]", "").replaceAll("\\..*", "");
		// convert List<Byte> to byte[]
		Byte[] bData = data.toArray(new Byte[data.size()]);
		byte[] useableData = new byte[bData.length];
		for (int i = 0; i < bData.length; i++) {
			useableData[i] = bData[i];
		}
		// determine lock status
		boolean lock = LOCK_FILES;
		if (comp.getParam("lock") != null)
			lock = comp.getBooleanParam("lock");
		// create the file
		tif.addVarEntry(TIFile.createProgramEntry(TIFile.CALC_83, name, lock, useableData));
		byte[] output = tif.buildFile();
		List<Byte> finalOutput = new ArrayList<Byte>(output.length);
		// convert byte[] to List<Byte>
		for (int i = 0; i < output.length; i++)
			finalOutput.add(output[i]);
		return finalOutput;
	}
}
